package jdbc;

import java.sql.*;

public class JDBCDemo1 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tedu?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true",
                "root",
                "root");
        System.out.println("数据库连接建立成功");
        /*
        Statement statement = conn.createStatement();
        String sql = "CREATE TABLE userinfo(\n" +
                "                id INT PRIMARY KEY AUTO_INCREMENT,\n" +
                "                username VARCHAR(32),\n" +
                "                password VARCHAR(32),\n" +
                "                nickname VARCHAR(32),\n" +
                "                age INT(3))";

        Statement state = conn.createStatement();
        String sql = "CREATE TABLE userinfo( " + " id INT PRIMARY KEY AUTO_INCREMENT, " + " username VARCHAR(32), " + " password VARCHAR(32), " + " nickname VARCHAR(32), " + " age INT(3) " + " )";
        state.execute(sql);
        System.out.println("执行成功");
        conn.close();
        */
        try {
            // 检查userinfo表是否已存在
            DatabaseMetaData metaData = conn.getMetaData();
            ResultSet resultSet = metaData.getTables(null, null, "userinfo", new String[]{"TABLE"});

            if (resultSet.next()) {
                // 表已存在
                System.out.println("表已被创建");
            } else {
                // 表不存在，创建表
                Statement statement = conn.createStatement();
                String sql = "CREATE TABLE userinfo(\n" +
                        "                id INT PRIMARY KEY AUTO_INCREMENT,\n" +
                        "                username VARCHAR(32),\n" +
                        "                password VARCHAR(32),\n" +
                        "                nickname VARCHAR(32),\n" +
                        "                age INT(3))";
                statement.executeUpdate(sql);
                System.out.println("表创建成功");
                statement.close();
            }

            resultSet.close();
        } catch (SQLException e) {
            System.out.println("操作数据库时发生错误: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            if (conn != null) {
                try {
                    conn.close();
                    System.out.println("数据库连接已关闭");
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}